<?php

namespace app\uapi\controller;

use app\admin\model\KnscyComment;
use app\admin\model\KnscyOrders;
use app\common\controller\ApiController;
use app\common\service\UploadService;
use think\facade\Db;

/**
 * 拥有演示项目的数据给出
 */
class Demo extends  ApiController
{

    public static $needLoginAction = [

        'upload', //上传图片
        'getEditComment', //用户编辑发布的评论
        'postComment', //用户发布
        'deleteComment',//删除评论
    ];

    public function option()
    {
        $data =  [
            'appName' => '学生综合评价管理系统',
            'version' => '1.0',
            'tag' => '考评管理每个学生',
            'logo'=> get_full_url( sysconfig('company','company_logo')),
        ];

        $this->success("success",$data);
    }


    public function upload()
    {
        $this->checkPostRequest();
        $data = [
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'file|指定上传类型有误'  => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = UploadService::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {

            $this->success($upload['msg'], [
                'url' => get_full_url($upload['url']),
                'save_url'=>$upload['url']
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }


    /**
     * 用户删除自己的评论
     */
    public function deleteComment(){
        $id = $this->request->post('id');
        $model = new KnscyComment();
        $rows = $model->whereIn('id',$id)->select();
        if($rows){
            $rows->delete();
            $this->success('success');
        }
        $this->error('参数有误');
    }
    /**
     * 用户发布保存评论
     * @return void
     */
    public function postComment()
    {
        $post = $this->request->post();
        $rule = [
            'nickname|昵称' => 'require|min:2|max:20',
            'content|综合评价' => 'require|min:10',
            'avatar|图片' => 'require',
            'score|学号' => 'require|number|max:10|unique:comment,score',
        ];
        $this->validate($post, $rule);
        $post['user_id'] = $this->user_id;
        $post['status'] = 0;// 进入审核阶段
        unset($post['thumbs']);

        if(!empty($post['id'])){
            $model = KnscyComment::where('id', $post['id'])->find();
        }else{
            $model = new KnscyComment();
        }

        $save = $model->save($post);
        $this->success('success', $save);
    }

    /**
     * 获取某条评论用于编辑
     * @return void
     */
    public function getEditComment()
    {
        $id = $this->request->post('id', 0);
        $info = KnscyComment::where('id', $id)->find();
        //处理图片用于编辑
        $arr = explode("|",$info['thumbs']);
        $thumbs = [];
        foreach($arr as $key=> $log){
            $thumbs[$key]['url'] = get_full_url($log);
            $thumbs[$key]['save_url'] = $log;
        }
        $info['avatar_url'] = get_full_url($info['avatar']);
        $info['thumbs'] =  $thumbs;
        $this->success('success',$info);
    }
    /**
     * 评论数据
     */
    public function recentComment(){
        $limit = $this->request->post('limit', 5);
        $page = $this->request->post('page', 1);
        $sortField = $this->request->post('sortField');
        $sortOrder = $this->request->post('sortOrder');
        $keyword = $this->request->post('keyword');


        $order = Db::raw("id desc");
        if($sortField){
            $order =  Db::raw("$sortField " . explode("end",$sortOrder)[0]);
        }

        $list = KnscyComment::where('status',"=", 0)
            ->when(!empty($keyword), function ($query) use ($keyword) {
                $query->where('nickname|score', 'like', "%{$keyword}%");

            })
            ->order( $order)
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function($item){
                $arr = explode("|",$item['thumbs']);
                foreach($arr as $key=> $log){
                    $arr[$key] = get_full_url($log);
                }
                $item['thumbs'] =  $arr;
                $item['avatar'] = get_full_url($item['avatar']);
                $item['date_label'] = date('Y-m-d',strtotime($item['create_time']));
            });
        $this->success('success', $list);
    }
}